/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2023. All rights reserved.
 *
 */

import path from 'path';

import { CommonConst } from '../../const/common-const.js';
import { TaskNames } from '../common/task-names.js';
import { GenerateLoaderJson } from '../generate-loader-json.js';
import { LegacyCompileResource } from '../legacy-tasks/legacy-compile-resource.js';
import { LegacyGenerateJsManifest } from '../legacy-tasks/legacy-generate-js-manifest.js';
import { LegacyGenerateLoaderJson } from '../legacy-tasks/legacy-generate-loader-json.js';
import { LegacyProcessResource } from '../legacy-tasks/legacy-process-resource.js';
import { PreCheckSyscap } from '../pre-check-syscap.js';
import { ModuleTaskService } from '../service/module-task-service.js';
import { TargetTaskService } from '../service/target-task-service.js';
import { OhosHapTask } from '../task/ohos-hap-task.js';

import { ReplaceUnitTestIndexFile } from './replace-unit-test-index-file.js';

/**
 * unit test编译资源
 *
 * @2023/4/24
 */
export class BuildUnitTestHook extends OhosHapTask {
  protected syscapJsonPath: string;
  protected isFaMode: boolean;

  constructor(targetService: TargetTaskService, isFaMode: boolean) {
    super(targetService, TaskNames.Task.BUILD_UNIT_TEST_RES);
    this.isFaMode = isFaMode;
    this.syscapJsonPath = path.resolve(this.service.getModuleModel()?.getSourceRootByTargetName(), CommonConst.SYSCAP_JSON);
  }

  protected doTaskAction(): void {
    // this is a hook task for depends diff task
    // task do nothing
  }

  initTaskDepends() {
    if (this.isFaMode) {
      this.declareDepends(LegacyGenerateLoaderJson.name);
      this.declareDepends(LegacyGenerateJsManifest.name);
      this.getLegacyUnitTestCompileRes();
    } else {
      this.declareDepends(GenerateLoaderJson.name);
      this.declareDepends(ReplaceUnitTestIndexFile.name);
    }

    this.declareDepends(PreCheckSyscap.name);
  }

  private getLegacyUnitTestCompileRes() {
    const relatedEntryModules = this.service.getRelatedEntryModules();
    const moduleType = this.service.getModuleModel().getModuleType();
    if (ModuleTaskService.checkEntryModules(moduleType, relatedEntryModules)) {
      for (const entryName of relatedEntryModules!) {
        this.createTaskAndDepends(entryName);
      }
    } else {
      this.createTaskAndDepends();
    }
  }

  private createTaskAndDepends(entryName?: string) {
    const processResourceTask = new LegacyProcessResource(this.targetService, entryName);
    const compileResourceTask = new LegacyCompileResource(this.targetService, entryName);
    this.module.registry(processResourceTask);
    this.module.registry(compileResourceTask);
    processResourceTask.initTaskDepends();
    compileResourceTask.initTaskDepends();
    this.declareDepends(compileResourceTask.getName());
  }
}
